#!/bin/sh

start_item() {
	toy=$1

	mkdir -p "toys/$toy/"
	while ! mkdir "toys/$toy/.lock"
	do
		sleep 1
		pid=$(cat "toys/$toy/.lock/pid")
		if [ -n "$pid" ] && ! kill -0 "$pid"
		then
			rm -r "toys/$toy/.lock"
		fi
	done

	echo $$ >"toys/$toy/.lock/pid"
	set -e
	lastItem=$(find "toys/$toy/" -type d -maxdepth 1 -mindepth 1 | grep -E '[0-9]+' | sed "s|toys/$toy/||" | sort -n | tail -n 1)
	lastItem=${lastItem:--1}
	currentItem=$(( lastItem + 1 ))
	mkdir "toys/$toy/$currentItem"

	while [ "$(find "toys/$toy/" -type d -maxdepth 1 -mindepth 1 | grep -Ec '[0-9]+')" -gt 6 ]
	do
		earliestItem=$(find "toys/$toy/" -type d -maxdepth 1 -mindepth 1 | grep -E '[0-9]+' | sed "s|toys/$toy/||" | sort -n | head -n 1)
		rm -rf "toys/$toy/$earliestItem" "toys/$toy/$earliestItem.log" "toys/$toy/$earliestItem.exit"
	done

	rm -r "toys/$toy/.lock"

	touch "toys/$toy/$currentItem.log"
	# shellcheck disable=SC2154
	podman run -d --timeout 86400 --add-host git.apiote.xyz:195.80.133.44 --log-opt=path="$docroot/toys/$toy/$currentItem.log" --name "item_${toy}_$currentItem" "toy_$toy" "$currentItem" >/dev/null 2>&1

	printf "%s" "$currentItem"
}

stop_item() {
	toy=$1
	item=$2
	if ! podman ps | grep -q "item_${toy}_$item"
	then
		return
	fi
	podman stop "item_${toy}_$item"
}
